package com.demo;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;

import java.util.Base64;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HutoolHttpTestsDemo {
    // 得到项目信息
    public void http() {
        // 拼接客户 ID 和客户密钥并使用 base64 编码
        String plainCredentials = customerKey + ":" + customerSecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // 创建 authorization header
        String authorizationHeader = "Basic " + base64Credentials;
        //方法一：使用工具类转换
        //JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        String result = HttpRequest.get("https://api.agora.io/dev/v1/projects")
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .execute().body();
        Console.log(result);
    }

    // 客户 ID
    final String customerKey = "b";
    // 客户密钥
    final String customerSecret = "c";
    // 拼接客户 ID 和客户密钥并使用 base64 编码
    String plainCredentials = customerKey + ":" + customerSecret;
    String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
    // 创建 authorization header
    String authorizationHeader = "Basic " + base64Credentials;
    //String token = "006c658042b097a4e15a2dc72afc2ee7d48IACza50c9ytFepH5fDpkRI10VPK2JRfZDAjaddTBOosqI3cVWtYAAAAAEAAlZZC8yj2LYQEAAQDKPYth";
    String appId = "a";
    String mode = "mix"; //单流individual  合流mix
    String cname = "11";
    String uid = "1";
    //400错误： 新创建的项目要开启云录制权限

    //七牛配置
    String qn_accessKey = "d";
    String qn_bucket = "mefly-rtc";
    String qn_secretKey = "e";

    public void acquireAndStart() {
        //language=JSON
        String jsonStr = "{\n" +
                "  \"cname\": \"{}\",\n" +
                "  \"uid\": \"{}\",\n" +
                "  \"clientRequest\": {}\n" +
                "}";
        jsonStr = StrUtil.format(jsonStr, cname, uid);
        //方法一：使用工具类转换
        //JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        String result = HttpRequest.post(StrUtil.format("https://api.agora.io/v1/apps/{}/cloud_recording/acquire", appId))
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .body(jsonStr)
                .execute().body();
        Console.log(JSONUtil.formatJsonStr(result));
        String resourceId = (String) JSONUtil.parseObj(result).get("resourceId");
        Console.log(resourceId);
        if (!StringUtils.isEmpty(resourceId)) {
            start(resourceId);
        }
    }

    // 设录制大屏给uid为 2的用户
    public void start(String resourceId) {
        //language=JSON
        String jsonStr = "{\n" +
                "    \"uid\": \"{}\",\n" +
                "    \"cname\": \"{}\",\n" +
                "    \"clientRequest\": {\n" +
                //"       \"token\": \"{}\",\n" +
                "        \"recordingConfig\": {\n" +
                "            \"maxIdleTime\": 30,\n" +
                "            \"streamTypes\": 2,\n" +
                "            \"channelType\": 0," +
                "\n" +
                "            \"subscribeUidGroup\": 0,\n" +
                "            \"transcodingConfig\":{\"width\":640,\"height\":360,\"fps\":30,\"bitrate\":500,\"mixedVideoLayout\":2,\"maxResolutionUid\":\"2\"}\n" +
                "        },\n" +
                "        \"recordingFileConfig\": {\n" +
                "            \"avFileType\": [\n" +
                "                \"hls\",\"mp4\"\n" +
                "            ]\n" +
                "        },\n" +
                "        \"storageConfig\": {\n" +
                "            \"accessKey\": \"{}\",\n" +
                "            \"region\": 1,\n" +
                "            \"bucket\": \"{}\",\n" +
                "            \"secretKey\": \"{}\",\n" +
                "            \"vendor\": 0" +
                "\n" +
                "        }\n" +
                "    }\n" +
                "}";
        jsonStr = StrUtil.format(jsonStr, uid, cname, qn_accessKey, qn_bucket, qn_secretKey);
        //方法一：使用工具类转换
        //JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        String url = StrUtil.format("https://api.agora.io/v1/apps/{}/cloud_recording/resourceid/{}/mode/{}/start",
                appId,
                resourceId,
                mode);
        String result = HttpRequest.post(url)
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .body(jsonStr)
                .execute().body();
        Console.log(JSONUtil.parseObj(result).get("sid"));
    }

    public void stop(String resourceId, String sid) {
        //language=JSON
        String jsonStr = "{\n" +
                "    \"cname\": \"{}\",\n" +
                "    \"uid\": \"{}\",\n" +
                "    \"clientRequest\": {\n" +
                "        \"async_stop\": false\n" +
                "    }\n" +
                "}";
        jsonStr = StrUtil.format(jsonStr, cname, uid);
        String url = StrUtil.format("https://api.agora.io/v1/apps/{}/cloud_recording/resourceid/{}/sid/{}/mode/{}/stop",
                appId, resourceId, sid, mode);
        String result = HttpRequest.post(url)
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .body(jsonStr)
                .execute().body();
        Console.log(JSONUtil.formatJsonStr(result));
    }

    public void updateLayout(String resourceId, String sid, String thisUid) {
        //language=JSON
        String jsonStr = "{\n" +
                "    \"cname\": \"{}\",\n" +
                "    \"uid\": \"{}\",\n" +
                "    \"clientRequest\": {\n" +
                "        \"maxResolutionUid\": \"{}\",\n" +
                "        \"mixedVideoLayout\": 2\n" +
                "    }\n" +
                "}";
        jsonStr = StrUtil.format(jsonStr, cname, uid, thisUid);
        String url = StrUtil.format("https://api.agora.io/v1/apps/{}/cloud_recording/resourceid/{}/sid/{}/mode/{}/updateLayout",
                appId, resourceId, sid, mode);
        String result = HttpRequest.post(url)
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .body(jsonStr)
                .execute().body();
        Console.log(JSONUtil.formatJsonStr(result));
    }

    public void query(String resourceId, String sid) {
        String url = StrUtil.format("https://api.agora.io/v1/apps/{}/cloud_recording/resourceid/{}/sid/{}/mode/{}/query",
                appId, resourceId, sid, mode);
        String result = HttpRequest.get(url)
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .execute().body();
        Console.log(JSONUtil.formatJsonStr(result));
    }

    public static void main(String[] args) {
        String resourceId = "nUwUbQf9Zg6tsgtLslGnDg0lk8RYaUE09pqOuSIgwfzQ8GOCGy53nrZ7U0piWHJm3GCL9L11IwdFApPUKxF80cFzw5a6YngdxVAui03Ec68ruOfEnDEbs1TZxGXtF1uCN961fL9lbYzg1Myj0HowWN7Zx72PKb9EZw3pVvczAOpxVHjsQ3Sm7XpisTlvn1ozfCMjfetzknWuMPYfGCoUlKpeTqhl6MT0dIyBeXKo_WtBZPR-2WF-ZTL2NcMhWMAJSudO8oqqt3TN-jH8jhgo556_mtL8BK5B0GXJr6KEWzoAHUlHmmpmxQSnyE6sZHP2uJYrYZ4Qg8Ox49pGUwb1xA";
        String sid = "e90c3ff4f44fe40a43d471b4a00b64bf";
        //new HutoolHttpTestsDemo().acquireAndStart();
        //new HutoolHttpTestsDemo().updateLayout(resourceId, sid, "3");
        //new HutoolHttpTestsDemo().query(resourceId, sid);


        //new HutoolHttpTestsDemo().start();
        new HutoolHttpTestsDemo().stop(resourceId, sid);
    }
}
